﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.Data;
using System.IO;
using DevScope.SharePoint.Utils.BulkDelete.Logging;
using DevScope.SharePoint.Utils.BulkDelete.Helpers;

namespace DevScope.SharePoint.Utils.BulkDelete.Helpers
{
    public static class SharePointHelper
    {
        /// <summary>
        /// Updates the list.
        /// </summary>
        /// <param name="webUrl">The web URL.</param>
        /// <param name="listName">Name of the list.</param>
        /// <param name="batchNode">The batch node.</param>
        public static void UpdateList(string webUrl, string listName, XmlNode batchNode)
        {
            #region Validations
            if (string.IsNullOrEmpty(webUrl))
                throw new ArgumentNullException("webUrl");
            if (string.IsNullOrEmpty(listName))
                throw new ArgumentNullException("listName");
            if (batchNode == null)
                throw new ArgumentNullException("batchNode");
            #endregion

            XmlNode ndResult = null;

            using (DevScope.SharePoint.Utils.BulkDelete.SPWSLists.Lists proxy = new DevScope.SharePoint.Utils.BulkDelete.SPWSLists.Lists())
            {
                proxy.Url = WebHelper.UrlCombine(webUrl, Constants.SPWSLists);
                proxy.Timeout = Constants.DefaultValues.ProxyTimeout;
                proxy.Credentials = CredentialCache.DefaultNetworkCredentials;                
                ndResult = proxy.UpdateListItems(listName, batchNode);
            }

            //XPath to obtain the 'Result' that as an error...
            XmlNode ndErrorResult = ndResult.SelectSingleNode("//*[local-name()='Result' and ./*[local-name()='ErrorCode'] != '0x00000000']");

            if (ndErrorResult != null)   
                throw new ApplicationException(string.Format("Error on UpdateListItems, list '{0}' on web: '{1}', Error result xml: '{2}'."
                                        , listName
                                        , webUrl
                                        , ndErrorResult.OuterXml));
        
        }

        /// <summary>
        /// Queries the list.
        /// </summary>
        /// <param name="webUrl">The web URL.</param>
        /// <param name="listName">Name of the list.</param>
        /// <param name="rowLimit">The row limit.</param>
        /// <param name="queryNode">The query node.</param>
        /// <param name="viewFieldsNode">The view fields node.</param>
        /// <param name="queryOptionsNode">The query options node.</param>
        /// <returns></returns>
        public static System.Data.DataTable QueryList(string webUrl, string listName
            ,int rowLimit, XmlNode queryNode, XmlNode viewFieldsNode, XmlNode queryOptionsNode)
        {
            #region Validations
            if (string.IsNullOrEmpty(webUrl))
                throw new ArgumentNullException("webUrl");
            if (string.IsNullOrEmpty(listName))
                throw new ArgumentNullException("listName");
            #endregion

            XmlNode ndResult = null;

            using (DevScope.SharePoint.Utils.BulkDelete.SPWSLists.Lists proxy = new DevScope.SharePoint.Utils.BulkDelete.SPWSLists.Lists())
            {                
                proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                proxy.Timeout = Constants.DefaultValues.ProxyTimeout;
                proxy.Url = WebHelper.UrlCombine(webUrl, Constants.SPWSLists);
                ndResult = proxy.GetListItems(listName, null, queryNode
                        , viewFieldsNode, rowLimit.ToString(), queryOptionsNode, null);
            }            

            XmlNode ndData = ndResult.SelectSingleNode("//*[local-name()='data']");            
            
            if (ndData.Attributes["ItemCount"].Value == "0")
                return null;

            using (DataSet ds = new DataSet())
            {
                using (StringReader input = new StringReader(ndData.OuterXml))
                {
                    using (XmlTextReader reader = new XmlTextReader(input))
                    {
                        ds.ReadXml(reader);
                    }
                }

                return ds.Tables["row"];
            }
        }
    }
}
